# -*- coding:UTF-8 -*-
import pymongo

class ConnMongo:
    def __init__(self, host, port, dbname, tbname, user, pwd):
        self.host = host
        self.port = int(port)
        self.user = user
        self.pwd = pwd
        self.dbname = dbname
        self.tbname = tbname
        self._conn = None
        self.db = self.connMongo()

    #连接
    def connMongo(self):
        db = False
        try:
            conn = pymongo.MongoClient(self.host, self.port)
            self._conn = conn
            db_auth = conn.admin
            authResult = db_auth.authenticate(self.user,self.pwd)
            db = conn[self.dbname]
            if not authResult:
                db = False
        except Exception,data:
            db = False
        return db

    # 查找
    def find(self, param, temp):
        res = False
        try:
            collection = self.db[self.tbname]
            query = {}
            query[param] = temp
            res = collection.find(query)
        except Exception, data:
            res = False
        return res

    #删除
    def delete(self, param, temp):
        flag = False
        try:
            collection = self.db[self.tbname]
            query = {}
            query[param] = temp
            collection.remove(query)
            flag = True
        except Exception, data:
            flag = False
        return flag

    #关闭
    def close(self):
        flag = False
        if(self._conn):
            try:
                self._conn.close()
                flag = True
            except Exception,data:
                flag = False
        return flag